'use strict';
const mongoose = require('mongoose');
const async = require('async');

var dataApi = (schemObj, objName) => {

    //const _model = mongoose.model(objName, schemObj);

  /**
   * 插入数据
   * @param obj
   * @param callback
   */
  schemObj.statics.insertOne = (obj, callback) => {
        var _Model=mongoose.model(objName, schemObj);
        var entity = new _Model(obj);
        entity.save(function (err, newObj) {
            callback(err,entity);
        });
    }

  /**
   * 更新数据
   * @param conditions
   * @param update
   * @param callback
   */
    schemObj.statics.findAndUpdate = (conditions, update, callback) => {
        if (!conditions || conditions === {}) {
            throw new Error("更新条件不能为空");
        }
        mongoose.model(objName, schemObj).findOneAndUpdate(conditions, update, { new : true,  runValidators: true }, function (err, doc) {
            callback(err,doc);
        });
    };

    /**
     * 删除数据
     * @param conditions
     * @param callback
     */
    schemObj.statics.findAndRemove = (conditions, callback) => {
       if (!conditions || conditions === {}) {
           throw new Error("删除条件不能为空");
       }
        mongoose.model(objName, schemObj).findOneAndRemove(conditions, function (err,doc) {
            callback(err,doc);
        })
    };

    schemObj.statics.finds = (conditions, callback) => {
      mongoose.model(objName, schemObj).find(conditions, function (err, docs) {
          if (err) {
              throw err;
          } else {
              callback(docs);
          }
      })
    }

  /**
   *
   * @param page
   * @param pageSize
   * @param queryParams
   * @param queryFields
   * @param populate
   * @param sortParams
   * @param callback
   */
    schemObj.statics.pageQuery = (page = 1, pageSize, queryParams = {}, queryFields = {}, populate = '', sortParams, callback) => {

      var start = (page - 1) * pageSize;
      var _Model = mongoose.model(objName, schemObj);
      var $page = {};

      async.parallel({
        count: function (done) {  // 查询数量
          _Model.count(queryParams).exec(function (err, count) {
            done(err, count);
          });
        },
        records: function (done) {   // 查询一页的记录
          if(populate){
            _Model.find(queryParams,queryFields).populate(populate).skip(start).limit(pageSize).sort(sortParams).exec(function (err, doc) {
              done(err, doc);
            });
          }else{
            _Model.find(queryParams,queryFields).skip(start).limit(pageSize).sort(sortParams).exec(function (err, doc) {
              done(err, doc);
            });
          }
        }
      }, function (err, results) {
        $page.pagination = {
          current : Number(page),
          pageSize : pageSize,
          total : results.count
        };
        $page.results = results.records;
        callback(err, $page);
      });
    };

}
module.exports = dataApi;